# -*- coding: utf-8 -*-

from cgnpc.items import cgnpcSku, cgnpcItem
from zc_core.model.items import Catalog, ItemDataSupply
import json
from zc_core.util.http_util import *


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    json_data = json.loads(response.text)
    for data1 in json_data['data']:
        cat1_name = data1['nodeName']
        cat1_id = data1['nodeCode']
        cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat11)
        for data2 in data1['childNodeList']:
            cat2_name = data2['nodeName']
            cat2_id = data2['nodeCode']
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for data3 in data2['childNodeList']:
                cat3_name = data3['nodeName']
                cat3_id = data3['nodeCode']
                cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


def parse_total_page(response):
    json_data = json.loads(response.text)

    return int(json_data['data']['result']['totalPage'])


# 解析sku列表
def parse_spu(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    josn_data = json.loads(response.text)
    skus = list()
    for i in josn_data['data']['result']['root']:
        sku = cgnpcSku()
        sku['spuId'] = str(i['productId'])
        sku['batchNo'] = batch_no
        # sku['brandName'] = i['productName']
        # sku['brandCode'] = i['brandCode']
        # unit = i.get('unitName', '')
        # if unit != '':
        #     sku['unit'] = unit
        sku['soldCount'] = i['soldNum']
        # sku['skuImg'] = fill_link(i['imageUrl'], base="https://mall.cgnpc.com.cn")
        # sku['supplierName'] = i['supplierName']
        sku['catalog1Id'] = catalog1Id
        sku['catalog1Name'] = catalog1Name
        sku['catalog2Id'] = catalog2Id
        sku['catalog2Name'] = catalog2Name
        sku['catalog3Id'] = catalog3Id
        sku['catalog3Name'] = catalog3Name
        skus.append(sku)
    return skus


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    soldCount = meta.get('soldCount')
    json_data = json.loads(response.text)

    for i in json_data['data']['productSkuDtos']:

        result = cgnpcItem()
        # 批次编号
        result['batchNo'] = batch_no
        # 平台商品ID（用于业务系统）
        result['skuId'] = i['skuCode']
        supplier_sku_code = i['skuCode']
        result['supplierSkuCode'] = supplier_sku_code
        supplier_sku_id = supplier_sku_code
        result['supplierSkuId'] = supplier_sku_id
        sku_name = json_data['data']['productName']
        result['skuName'] = sku_name
        brand_name = json_data['data']['brandName']
        result['brandName'] = brand_name
        origin_price = i['marketPrice']
        sale_price = i['price']
        if origin_price == '':
            origin_price = sale_price
        if not origin_price:
            origin_price = 0
        if not sale_price:
            sale_price = 0
        result['originPrice'] = float(origin_price)
        result['salePrice'] = float(sale_price)
        result['soldCount'] = soldCount
        sku_img = fill_link(json_data['data']['imageUrl'], base='https://mall.cgnpc.com.cn/')
        result['skuImg'] = sku_img
        result['spuId'] = str(i['productId'])
        unit = i['unitName']
        result['unit'] = unit
        supplier_id = json_data['data']['supplierId']
        result['supplierId'] = str(supplier_id)
        supplier_name = json_data['data']['supplierName']
        result['supplierName'] = supplier_name
        on_sale_time = json_data['data']['updateTimeStr']
        result['onSaleTime'] = on_sale_time
        sale_status = json_data['data']['shelveStatusStr']
        result['saleStatus'] = sale_status
        delivery_date = json_data['data']['deliveryDate']
        if delivery_date:
            delivery_date = delivery_date.replace('天内', '')
            result['deliveryDay'] = delivery_date
        result['catalog1Name'] = catalog1Name
        result['catalog1Id'] = catalog1Id
        result['catalog2Name'] = catalog2Name
        result['catalog2Id'] = catalog2Id
        result['catalog3Name'] = catalog3Name
        result['catalog3Id'] = catalog3Id
        result['stock'] = str(i['inventory'])

        yield result


def parse_prices(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')

    json_data = json.loads(response.text)
    item = ItemDataSupply()
    item['batchNo'] = batch_no
    item['skuId'] = sku_id
    data = [i for i in json_data['data']['result']['productPriceVOList'] if i.get('skuCode') == sku_id][0]
    item['originPrice'] = data['price'] if float(data['marketPrice']) == 0 or float(
        data['marketPrice']) == 0.0 else float(data['marketPrice'])
    item['salePrice'] = data['price']
    item['skuCode'] = data['skuCode']
    return item
